package com.mego.zbss.activity_fragment;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.mego.zbss.R;
import com.mego.zbss.util.Constant;
import com.mego.zbss.view.BaseViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    DrawerLayout mDrawerLayout;
    String mUrl;
    TextView tvBaseTitle;
    private ProgressBar pbWebView;
    private WebView wvWebView;

    ListView mListSettings = null;
    MyAdapter mMyAdapter;
    TextView change_name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        tvBaseTitle = (TextView) findViewById(R.id.tvBaseTitle);
        tvBaseTitle.setText("钻豹视商-大陆");
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        mUrl = getWebByIndex(0);
        pbWebView = (ProgressBar) findViewById(R.id.pbWebView);
        wvWebView = (WebView) findViewById(R.id.wvWebView);

        ImageView change_icon = (ImageView) findViewById(R.id.change_icon);
        change_name = (TextView) findViewById(R.id.change_name);
        change_icon.setImageResource(settings_icons[7]);
        change_name.setText(TOP_MENUS[7]);

        mListSettings = (ListView) findViewById(R.id.settings_list);
        mMyAdapter = new MyAdapter(this);
        mListSettings.setAdapter(mMyAdapter);
        mListSettings.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                onSettingItem(position);
            }
        });

        initData();
    }

    void initData() {

        WebSettings webSettings = wvWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        wvWebView.requestFocus();

        // 设置setWebChromeClient对象
        wvWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
//                tvBaseTitle.setText(StringUtil.getTrimedString(title));
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                pbWebView.setProgress(newProgress);
            }
        });

        wvWebView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
                    if (wvWebView.canGoBack()) {
                        wvWebView.goBack();
                        firstTime = 0;
                        return true;
                    } else {
                        checkExit();
                        return true;
                    }
                }
                return false;
            }
        });

        wvWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                wvWebView.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
//                tvBaseTitle.setText(StringUtil.getTrimedString(wvWebView.getUrl()));
                pbWebView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
//                tvBaseTitle.setText(StringUtil.getTrimedString(wvWebView.getTitle()));
                pbWebView.setVisibility(View.GONE);
            }
        });

        wvWebView.loadUrl(mUrl);
    }

    private static final String[] TOP_MENUS = {
            "商城入口", "入驻商户", "钻石商城", "团购", "优惠卷中心",
            "我的收藏", "申请入驻全返利商城", "切换至钻豹台湾商城"};

    private static final String[] TOP_MENUS_TW = {
            "商城入口", "入駐商戶", "鉆石商城", "團購", "優惠卷中心",
            "我的收藏", "申請入駐全返利商城", "切換至鉆豹大陸商城"};

    boolean _isTW = false;

    @Override
    public void onBackPressed() {
        if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
        } else {
//            super.onBackPressed();
            if (wvWebView.canGoForward()) {
                wvWebView.goForward();
            }
        }
    }

    private void onSettingItem(int position) {
        if (position == 7) {
            doChange(!_isTW);
        } else if (position >= 0 && position < 7) {
            mUrl = getWebByIndex(position);
            wvWebView.loadUrl(mUrl);
        }
        mDrawerLayout.closeDrawer(GravityCompat.START);
    }

    private void doChange(boolean isTW) {
        _isTW = isTW;
        mUrl = getWebByIndex(0);
        wvWebView.loadUrl(mUrl);
//        if (isTW) {
//            change_name.setText(TOP_MENUS_TW[7]);
//        } else {
//            change_name.setText(TOP_MENUS[7]);
//        }
    }

    public void onMenu(View v) {
        mDrawerLayout.openDrawer(GravityCompat.START);
    }

    public void onChangeTW(View v) {
        doChange(!_isTW);
//        mMyAdapter.notifyDataSetChanged();
        mDrawerLayout.closeDrawer(GravityCompat.START);
    }

    private String getWebByIndex(int index) {
        tvBaseTitle.setText("钻豹视商-大陆");
        String url = Constant.ZBSS_WEBSITE_0;
        switch (index) {
            default:
            case 0:
                break;
            case 1:
                url = Constant.ZBSS_WEBSITE_1;
                break;
            case 2:
                url = Constant.ZBSS_WEBSITE_2;
                break;
            case 3:
                url = Constant.ZBSS_WEBSITE_3;
                break;
            case 4:
                url = Constant.ZBSS_WEBSITE_4;
                break;
            case 5:
                url = Constant.ZBSS_WEBSITE_5;
                break;
            case 6:
                url = Constant.ZBSS_WEBSITE_6;
                break;
        }

        if (_isTW) {
            url = url.replace("mego_shopv2", "mego_shopv2_tw");
            url = url.replace("?i=12&", "?i=3&");
            tvBaseTitle.setText("鉆豹視商-臺灣");
        }

        return url;
    }

    @Override
    protected void onPause() {
        super.onPause();
        wvWebView.onPause();
    }

    @Override
    protected void onResume() {
        wvWebView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (wvWebView != null) {
            wvWebView.destroy();
            wvWebView = null;
        }
        wvWebView = null;
    }

    private long firstTime = 0;//第一次返回按钮计时

    void checkExit() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime > 2000) {
            Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
            firstTime = secondTime;
        } else {//完全退出
            moveTaskToBack(false);//应用退到后台
            System.exit(0);
        }
    }

    final static public int[] settings_icons = new int[]{R.mipmap.icon08, R.mipmap.icon01, R.mipmap.icon02, R.mipmap.icon03,
            R.mipmap.icon04, R.mipmap.icon05, R.mipmap.icon06, R.mipmap.icon07};


    public class MyAdapter extends BaseAdapter {

        private Context context;
        private List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();

        public MyAdapter(Context context) {
            this.context = context;
            data.clear();
            for (int i = 0; i < TOP_MENUS.length - 1 && i < settings_icons.length - 1; i++) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("title", TOP_MENUS[i]);
                data.add(map);
            }
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(parent.getContext()).inflate(
                        R.layout.tableitem_setting, parent, false);
            }

            ImageView settingIcon = BaseViewHolder.get(convertView, R.id.id_settingicon);
            TextView settingName = BaseViewHolder.get(convertView, R.id.id_settingname);

            if (position < settings_icons.length) {
                settingIcon.setImageResource(settings_icons[position]);
                if (_isTW) {
                    settingName.setText(TOP_MENUS_TW[position]);
                } else {
                    settingName.setText(TOP_MENUS[position]);
                }

            }
            return convertView;
        }
    }


}
